<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;

class BaseController extends Controller
{
    /**
     * json返回
     */
    protected function renderJson($code, $data = '', $message = null)
    {
        if ($message === null){
            $message = (String)status($code);
        }

        if (is_array($data) || is_object($data)){
            $retData = [
                'code'      => (int)$code,
                'message'   => $message,
                'data'      => $data,
                'timestamp' => time(),
//                'md5'       => md5(json_encode($data))
            ];
        }else{
            $_data = json_decode($data,true);
            $retData = [
                'code'      => (int)$code,
                'message'   => $message,
                'data'      => is_array($_data) ? $_data : $data,
                'timestamp' => time(),
//                'md5'       => md5(strval($data))
            ];
        }
        
        return response()
            ->json($retData);
    }
    
    /**
     * jsonp返回
     */
    public function renderJsonp($data, $callback = null)
    {
        if ($callback === null){
            $callback = request('callback','callback');
        }
        
        if (is_array($data) || is_object($data)){
            ;
        }elseif (is_numeric($data)){
            $data = (int)$data;
        }else{
            $data = '"'.$data.'"';
        }
        
        return response()
            ->json($data)
            ->withCallback($callback);
    }
}
